<?php

namespace app\api\controller;
use data\Json;
use think\Request;
use think\Cache;
use JPush\Client as JPush;
use app\common\model\CommunityMember;
use app\common\model\SupplierCalendar;
use app\common\model\ActivityCalendar;
use app\common\model\Travel;
use app\common\model\TravelMember;
use app\common\model\Activity;
use app\common\model\Oversea;
use app\admin\model\Community as CommunityModel;
use app\common\model\Travel as TravelModel;
/**
 * 社群api接口
 */
class Community extends Base
{
    protected $community_model = null;
    protected $token = null;
    protected $community = null;

    public function _initialize()
    {
        $this->community_model = model('User');
        $this->token = request()->header('token');
        //$this->community = $this->community_model->getUserInfo($this->token);
        $this->community = $this->community_model->get('1');
    }

    // 社群首页
    public function home()
    {
        if(!$this->community)return Json::json_send(1);

        $return = [];
        $return['auth'] = model('CommunityMember')->where(['community_id'=>$this->community['id'],'state'=>1])->count();
        $return['noauth'] = model('CommunityMember')->where(['community_id'=>$this->community['id'],'state'=>0])->count();
        $return['curve'] = [];
        foreach (getLastSexMonth() as $k => $v) {
            $month = date('Y-m',$v);
            $prevmonth = date('Y-m',strtotime('-1 month',$v));

            $themonth = getthemonth($month);
            $prevmonth = getthemonth($prevmonth);

            $thisMonthCount = model('CommunityMember')
            ->where(['community_id'=>$this->community['id'],'state'=>1])
            ->whereTime('entrytime', 'between', [$themonth[0], $themonth[1]])
            ->count();

            $prevMonthCount = model('CommunityMember')
            ->where(['community_id'=>$this->community['id'],'state'=>1])
            ->whereTime('entrytime', 'between', [$prevmonth[0], $prevmonth[1]])
            ->count();

            $growthRate = $thisMonthCount>$prevMonthCount && $prevMonthCount > 0 ? ($thisMonthCount-$prevMonthCount)/$prevMonthCount*100:0;

            $arr = ['month'=>date('m',$v),'number'=>$thisMonthCount,'growthrate'=>$growthRate];
            array_push($return['curve'], $arr);
        }

        $theWeek = gettheweek();

        $list = model('JpushData')
                ->field('msg,createtime')
                ->where(['type'=>2,'alias'=>$this->community['mobile']])
               // ->whereTime('createtime', 'between', [$theWeek[0], $theWeek[1]])
                ->select();
        $returnList = $days = [];
        foreach ($list as $k => $v) {
            $date = date('Y-m-d',$v['createtime']);
            $days[$date] = [];
        }
        foreach ($list as $k => $v) {
            $date = date('Y-m-d',$v['createtime']);
            array_push($days[$date],$v['msg']);
        }

        foreach ($days as $k => $v) {
            $arr = ['day' => $k,'messages' => $v];
            array_push($returnList, $arr);
        }

        $return['news']=$returnList;
        return Json::json_send(0,'',$return);
    }

    // 个人中心
    public function center()
    {
        if(!$this->community)return Json::json_send(1);
        $data = [
            'id'     =>  $this->community['id'],
            'avatar' =>  $this->community['avatar'],
            'person' =>  $this->community['person'],
            'name'   =>  $this->community['name'],
            'integration' =>  $this->community['integration'],// 活动收入
        ];
        return Json::json_send(0,'',$data);
    }

    // 个人资料
    public function info(Request $request)
    {
        if(!$this->community)return Json::json_send(1);
        if($request->isPost())
        {
            $data = input();
            if(request()->file('avatar'))
            {
                $data['avatar'] = $this->upload(request()->file('avatar'));
            }
            $result = $this->community_model->isUpdate(true)->allowField(true)->save($data,['id'=>$this->community['id']]);
            if( $result === false)
            {
                return Json::json_send(9);
            }

            if(isset($data['complete']) && $data['complete'] == 1 && $this->community['complete'] == 0){
                $this->community_model->where(['id'=>$this->community['id']])->setInc('integration', 5);
                $logData = [
                    'user_id' => $this->community['id'],
                    'desc'    => '完善个人信息',
                    'type'    => 0,
                    'integration' =>50,
                ];
                model('IntegrationLog')->save($logData);
            }
        }
        $community = $this->community_model->where('id',$this->community['id'])->find();
        $communityModel = new CommunityModel();
        $data = [
            'id' =>  $community['id'],
            'name' =>  $community['name'],
            'avatar' =>  $community['avatar'],
            'person' =>  $community['person'],
            'mobile' =>  $community['mobile'],
            'scale'  =>  $community['scale'],
            'setup_time' =>  $community['setup_time'],
            'setup_addr' =>  $community['setup_addr'],
            'is_pay'     =>  $community['is_pay'],
            'year_fee'   =>  $community['year_fee'],
            'city'       =>  $community['city'],
            'website'    =>  $community['website'],
            'wechat'     =>  $community['wechat'],
            'is_company' =>  $community['is_company'],
            'heldsdata'  =>  $communityModel->getHeldsdataTextAttr($community['heldsdata'],$community),// 活动收入
            'complete'   =>  $community['complete'],
        ];
        return Json::json_send(0,'',$data);
    }

    // 积分明细
    public function integration()
    {
        if(!$this->community)return Json::json_send(1);
        $integrationList = model('IntegrationLog')->where(['user_id'=>$this->community['id']])->select();
        $data=[];
        foreach ($integrationList as $k => $v) {
            $data[] = [
            'id' =>  $this->community['id'],
            'sum' =>  $this->community['integration'],
            'desc' =>  $v['desc'],
            'type' =>  $v['type'],
            'integration' =>  $v['integration'],
            'createtime' =>   $v['createtime'],
        ];
        }
        return Json::json_send(0,'',$data);
    }

    // 收入管理
    public function income()
    {
        if(!$this->community)return Json::json_send(1);
        $members = model('CommunityMember')->alias('cm')
                    ->join('user u','cm.user_id=u.id')
                    ->where(['cm.community_id'=>$this->community['id'],'paid'=>'1'])
                    ->order('entrytime desc')
                    ->select();
        $return = [];
        foreach ($members as $k => $v) {
            $return[] = [
                'member_id' => $v['user_id'],
                'member_name' => $v['name'],
                'member_avatar' => $v['avatar'],
                'entrytime' => $v['entrytime'],
                'fee' => $this->community['year_fee'],
            ];
        }
        return Json::json_send(0,'',$return);
    }

    // 海外活动列表
    public function overseas()
    {
        if(!$this->community)return Json::json_send(1);
        if(input('activityid'))
        {
            $activity_id = input('activityid');
            $oversea = model('Oversea')->get($activity_id);
            $oversea['all'] = $oversea['is_all'] == 1?"全包":"不全包";
            $this->view->assign('activity',$oversea);
            return $this->view->fetch('activity/overseainfo');// 活动商
        }


        $travel_id = input('travel_id',0);
        $travel = Travel::where(['id'=>$travel_id])->find();
        if(!$travel)return Json::json_send(4);

        if(empty(input('cityid')))
        {
            $city_id = input('cityid','5');// 默认美国
            $map['a.city_id'] = $city_id;
        }
        
        $condition = input('condition','');
        $map['a.name'] = ['like','%'.$condition.'%'];

        $overseaList = Oversea::alias('a')->where($map)->select();
        $data = [];
        foreach ($overseaList as $k => $v) {
            $data['activities'][]=[
                'id'    =>$v['id'],
                'poster'=>$v['poster'],
                'name'  =>$v['name'],
                'is_all'=>$v['is_all'],
                'time'  =>$v['time'],
                'fee'   =>$v['fee'],
            ];
        }

        $choosedList = model('Travel')->with('activity')->where(['id'=>$travel_id])->find();
        $choosed = [];
        if($choosedList)
        {
            foreach ($choosedList['activity'] as $k => $v) {
                array_push($choosed, ['activity_id'=>$v['id'],'name'=>$v['name'],'category'=>$v['category']]);
            }
           $data['choosed']  = $choosed;
        }

        return Json::json_send(0,'',$data);
    }

    // 活动列表
    public function activities()
    {
        if(!$this->community)return Json::json_send(1);
        $travel_id = input('travel_id',0);
        $travel = Travel::where(['id'=>$travel_id])->find();
        if(!$travel)return Json::json_send(4);
        $a_model = $travel['type']==1?model('Oversea'):model('Activity');
        if(input('activity_id'))
        {
            $activity_id = input('activity_id',0); 
            $activity= model('Activity')->get($activity_id);
           /* $url = config('url_domain_root').url('supplier/activities',['activityid'=>$activity_id]);
            return Json::json_send(0,'',$url);*/
            $return['poster'] = $activity['poster'];
            $return['url']    = config('url_domain_root').url('supplier/activities',['activityid'=>$activity_id]);
            // $url = config('url_domain_root').url('supplier/activities',['activityid'=>$activity_id]);
            return Json::json_send(0,'',$return);
        }

        if(input('siteid'))
        {
            $site_id = input('siteid',0); 
            $activity= model('Activity')->get($site_id);
            /*$url = config('url_domain_root').url('supplier/activities',['activityid'=>$site_id]);
            return Json::json_send(0,'',$url);*/
            $return['poster'] = $activity['poster'];
            $return['url']    = config('url_domain_root').url('supplier/activities',['activityid'=>$site_id]);
            // $url = config('url_domain_root').url('supplier/activities',['activityid'=>$activity_id]);
            return Json::json_send(0,'',$return);
        }

        $choosetimeList = getDateRange($travel['begintime'],$travel['endtime']);

        $map['a.is_delete'] = 0;

        $all_activities = Activity::alias('a')->where($map)->select();
        
        if(empty(input('more')))
        {
            $notIn = [];
            foreach ($all_activities as $k => $v) {
                $selected = Collection(ActivityCalendar::where(['is_delete'=>0,'activity_id'=>$v['id']])->column('time'))->toArray();
                if(count(array_diff($choosetimeList,$selected)) == 0)
                {
                   array_push($notIn, $v['id']);
                }
            }
            $map['a.id'] = ['not in',implode(",",$notIn)];
        }
        
        $map['s.type'] = ['<>','1'];

        if(input('is_site')){
             $map['a.is_site'] = '0';
        }

        $category = input('category','1');
        $map['a.category'] = $category;

        if(!empty(input('cityid')))
        {
            $city_id = input('cityid','1');
            $map['a.city_id'] = $city_id;
        }
        
        $condition = input('condition','');
        $map['a.name'] = ['like','%'.$condition.'%'];

        if(input('is_site') == 2)
        {
            $travel = TravelModel::with('activity')->where(['id'=>$travel_id])->find();
            $activityList = [];
            foreach ($travel['activity'] as $k => $v) {
                if($v['is_site'] == 0 && $v['pivot']['site_id'] == 0)
                {
                    $data = [
                        'id' => $v['id'],
                        'category' => $v['category'],
                        'name' => $v['name'],
                        'is_site' => $v['is_site'],
                        'time' => $v['time'],
                        'fee'=>$v['fee'],
                    ];
                    array_push($activityList, $data);
                }
            }
            //$return['activities'] = $activityList;
        }
        else
        {
            $activityList = Activity::alias('a')->join('supplier s','s.id=a.supplier_id')->field('a.id,a.category,a.poster,a.name,a.is_site,a.time,a.fee,s.name sponsor')->where($map)->select();
        }
        $return['activities'] = $activityList;
        $choosedList = model('Travel')->with('activity')->where(['id'=>$travel_id])->find();
        $choosed = [];
        if($choosedList)
        {
            foreach ($choosedList['activity'] as $k => $v) {
                array_push($choosed, ['activity_id'=>$v['id'],'name'=>$v['name'],'category'=>$v['category']]);
            }
           $return['choosed']  = $choosed;
        }
        return Json::json_send(0,'',$return); 
    }

    public function members(Request $request)
    {
        if(!$this->community)return Json::json_send(1);

        if(input('member_id'))
        {
            $member_id = input('member_id',0);
            $CommunityMember = CommunityMember::where(['community_id'=>$this->community['id'],'user_id'=>$member_id])->find();
            if(!$CommunityMember)return Json::json_send(9); 

            if($request->isPost())
            {
                $result = $CommunityMember->save(['state'=>1],['id'=>$CommunityMember['id']]);
                if(!$result)return Json::json_send(9);
                return Json::json_send(0);  
            }

            if(input('remind'))
            {
                $CommunityMember->save(['remind'=>1],['id'=>$CommunityMember['id']]);
                $user = model('User')->get($member_id );
                $jresult = jpush(2,$user['mobile'],'您的会员即将到期，请尽快续费');
                if($jresult)return Json::json_send(9); 
                return Json::json_send(0);  
            }
            
            $cmemberInfo =model('CommunityMember')->alias('cm')
                         ->join('user u','cm.user_id=u.id')
                         ->field('cm.user_id,u.avatar,u.name username,u.mobile,cm.entrytime,cm.expiretime,cm.paid,u.area,u.company,u.post,cm.state')
                         ->where(['cm.community_id'=>$this->community['id'],'user_id'=>$member_id])
                         ->find();
            $memberCommunities = model('CommunityMember')->alias('cm')
                                ->join('user u','cm.community_id=u.id')
                                ->field('cm.community_id,u.name')
                                ->where(['cm.user_id'=>$member_id])
                                ->select();

            $cmemberInfo['communitylist'] = $memberCommunities;
            return Json::json_send(0,'',$cmemberInfo); 
        }

        $map['cm.community_id'] = $this->community['id'];

        $state = input('state',0);
        if($state == 2) $map['cm.state'] = 0;

        $expire = input('expire',0);
        if($expire) 
        {
            $map['cm.expiretime'] = ['<',time()+30*24*3600];
            $map['cm.expiretime'] = ['>',time()];
        }

        $new = input('new',0);
        if($new) $map['cm.createtime'] = ['>',time()-30*24*3600];

        $condition = input('condition','');
        if(!empty($condition)){
            $map['u.name'] =['like',"%".$condition."%"];
        }

        $members = CommunityMember::alias('cm')->join('qz_user u','cm.user_id=u.id')->field('*,cm.state cmstate')->where($map)->select();
        $data = [];
        foreach ($members as $k => $v) {
            $data[]=[
                'user_id'      => $v['id'],
                'username'     => $v['name'],
                'avatar'  => $v['avatar'],
                'paid'    => $v['paid'],
                'state'   => $v['cmstate'],
                'remind'  => $v['remind'],
                'lastday' => count_days($v['expiretime'],time())
            ];
        }
        return Json::json_send(0,'',$data);
    }

    // 会员招募
    public function recruit()
    {
        if(!$this->community)return Json::json_send(1);
        return Json::json_send(0,'',['name'=>$this->community['name'],'qrcode'=>$this->community['qrcode']]);
    }

    // 我要推广
    public function promote(Request $request)
    {
        if(!$this->community)return Json::json_send(1);
        if($request->isPost())
        {
            $travel_id = input('travel_id');
            $travel = model('Travel')->get($travel_id);
            $commission = $travel['total_fee'] > $travel['cost'] ? ($travel['total_fee']-$travel['cost']) * 0.2 :0;
            $result = model('Travel')->save(['is_promote'=>1,'commission'=>$commission],['id'=>$travel_id]);
            if($result !== false)
            {
                return Json::json_send(0);
            }
            return Json::json_send(9);
        }

        $map = [
            'is_communite' => '0',
            'sponsor'      => $this->community['id'],
            'state'        => '1',
            'is_promote'   => '1',
        ];
        $promotes = collection(model('Travel')->with('activity')->where($map)->select())->toArray();
        $return = [];
        foreach ($promotes as $k => $v) {
            $titles = [];
            foreach ($v['activity'] as $key => $value) {
                array_push($titles, $value['name']);
            }

            $return[] = [
                'travel_id'    => $v['id'],
                'begintime'    => $v['begintime'],
                'endtime'      => $v['endtime'],
                'memebr_price' => $v['memebr_price'],
                'commission'   => $v['commission'],
                'titles'       => implode('+', $titles),
            ];
        }
        return Json::json_send(0,'',$return);
    }

    // 推广佣金
    public function commission()
    {
        if(!$this->community)return Json::json_send(1);
        $travel_id = input('travel_id');
        $travel = model('Travel')->get($travel_id);
        $parentList = model('TravelMember')->alias('tm')
                    ->join('user u','tm.parentid=u.id')
                    ->field("tm.parentid,count('tm.parentid') as number,u.name username,u.avatar")
                    ->where(['tm.travel_id'=>$travel_id,'tm.paid'=>1])
                    ->group('tm.parentid')
                    ->select();
        $return = [];
        $sum_commission=0;
        foreach ($parentList as $k => $v) {
            $sum_commission += $travel['commission']*$v['number'];
            $v['commission'] = $v['number']* $travel['commission'];
            $v['sum_commission'] = $sum_commission;
            $return[] = $v;
        }
        return Json::json_send(0,'',$return);
    }

     /**
     * 社群聊天记录
     */
    public function hxchat(Request $request)
    {
        if(!$this->community)return Json::json_send(1);
        $hx_groupid = empty(input('hx_groupid'))?$this->community['hx_groupid']:input('hx_groupid');
        $chats = model('Chat')
                  ->where('from|to', $hx_groupid)
                  ->where('chat_type', 'groupchat')
                  ->order('timestamp asc')
                  ->select();
        foreach ($chats as $ck => $cv) 
        {

            $chats[$ck]['payload'] = $payload = json_decode($cv['payload'],true);
            if(input('type'))
            {
                if($payload['bodies'][0]['type'] != input('type'))
                {
                    unset($chats[$ck]);
                }
            }
        }

        return Json::json_send(0,'',$chats);
    }

    public function groupinfo(Request $request)
    {
        if(!$this->community)return Json::json_send(1);
        $community_id = empty(input('community_id'))?$this->community['id']:input('community_id');
        $community = model('Community')->get($community_id);
        if($request->isPost())
        {
            $data = input();
            $data['group_notice'] = input('notice');
            $result = $this->community_model->allowField(true)->save($data,['id'=>$community_id]);
            if($result !== false)
            {
                return Json::json_send(0);
            }
            return Json::json_send(9);
        }

        if(input('user_id'))
        {
            $user_id = input('user_id');
            $user    = model('User')->get($user_id);
            if(input('add'))
            {
                // 添加群成员
                $result  = model('User')->addGroupMember($community['hx_groupid'],$user['hx_username']);
                return Json::json_send(0,'',$result);
            }

            if(input('delete'))
            {
                // 移除群成员
                $result  = model('User')->deleteGroupMember($community['hx_groupid'],$user['hx_username']);
              
                if(input('quan_id'))
                {
                    model('QuanFriends')->where(['quan_id'=>input('quan_id'),'user_id'=>$user_id])->delete();
                }
                else
                {
                    model('CommunityMember')->where(['community_id'=>$this->community['id'],'user_id'=>$user_id])->update(['is_remove'=>1]);
                }
                return Json::json_send(0,'',$result);
            }

            $info   =  model('CommunityMember')->alias('cm')
                                ->join('user c','cm.user_id=c.id')
                                ->field('*,cm.state cmstate')
                                ->where(['cm.user_id'=>$user_id,'community_id'=>$community_id])
                                ->find();
            $return = [
                'user_id'  => $user_id,
                'username' => $info['name'],
                'avatar'   => $info['avatar'],
                'mobile'   => $info['mobile'],
                'entrytime'    => $info['entrytime'],
                'expiretime'   => $info['expiretime'],
                'lastday'      => count_days($info['expiretime'],time()),
                'year_fee'     => $info['year_fee'],
                'area'         => $info['area'],
                'company'      => $info['company'],
                'post'         => $info['post'],
                'state'        => $info['cmstate'],
            ];

            return Json::json_send(0,'',$return);
        }

        $memberList = model('CommunityMember')->alias('cm')
                                ->join('user c','cm.user_id=c.id')
                                ->field('*,cm.state cmstate')
                                ->where(['cm.community_id'=>$community_id,'is_remove'=>0])
                                ->select();
        $return = [];
        $return['count']  = count($memberList)+1;
        $return['list'][0]=[
                'user_id'     =>  $community['id'],
                'avatar'      =>  $community['avatar'],
                //'hx_username'=>$v['hx_username'],
                'community_id'=>  $community['id'],
                'username'    =>  $community['name'],
                'state'       =>  1
            ];
        foreach ($memberList as $k => $v) {
            $return['list'][$k+1]=[
                'user_id'     =>  $v['user_id'],
                'avatar'      =>  $v['avatar'],
                //'hx_username'=>$v['hx_username'],
                'community_id'=>  $v['community_id'],
                'username'    =>  $v['name'],
                'state'       =>  $v['cmstate']
            ];
        }
        $return['notice']  = $community['group_notice'];
        $return['disturb'] = $community['disturb'];
        $return['is_pay']  = $community['is_pay'];
        return Json::json_send(0,'',$return);
    }



    // 入会二维码扫描结果
    public function checkin()
    {
        /////////
    }
}
